Can Navigator.push be used in ternary with Flutter

121

you can use ternary operator in any case. suppose in your above case (any true codition for example file ==null )?(Do some work if file is null ):Navigator.push( context, MaterialPageRoute(builder: (context) => Uploadimages()), ); (do alter work if the ternary codition is not true)

Share:
121
Carleton Y
Author by

Carleton Y

Entrepreneur learning Dart and Flutter to build a social app for my large number of social media followers. I started learning how to code with Dart and Flutter for the first time in my life in August 2021.

Updated on January 02, 2023

Comments

  • Carleton Y
    Carleton Y over 1 year

    I have a page with an app bar that has four tabs. On one of the tabs I am trying to use a condition in the build method to display a custom scroll view with specific content if the condition is true. And if the condition is false I want the user to be navigated to a brand new page that just has a list view and its own app bar that does not contain any tabs. Navigator.push being used as the second condition in the ternary throws an error. My goal in the code below is something like if file == null display content in Safe Area widget else navigate to a UploadItemsFormPage. I have been unable to figure out how to solve this challenge. I tried to remove a lot of the code to make it less to read but if necessary to help I can provide more of the code. The code will be refactored into different widgets but I thought that would make asking this question more complicated so it is all in one class for now. Thanks in advance for any help.

    class ShoppingAdminPage extends StatefulWidget {
      const ShoppingAdminPage({Key? key}) : super(key: key);
    
      @override
      State<ShoppingAdminPage> createState() => _ShoppingAdminPageState();
    }
    
    class _ShoppingAdminPageState extends State<ShoppingAdminPage> {
      final List<String> _tabs = <String>[
        TabNameString.upload,
        'Tab Two',
        'Tab Three',
        'Tab Four',
      ];
    
      TextEditingController descriptionController = TextEditingController();
      String productID = DateTime.now().microsecondsSinceEpoch.toString();
      TextEditingController priceController = TextEditingController();
      TextEditingController titleController = TextEditingController();
      bool isUploading = false;
      File? file;
    
      void clearImage() {
        setState(() {
          file = null;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return AdaptiveLayoutScaffold(
          drawer: const SideSheet(),
          landscapeBodyWidget: Container(),
          portraitBodyWidget: BrandTabController(
            actions: const [
              BrandPopUpMenu(),
            ],
            numberOfTabs: _tabs.length,
            pageName: PageName.shoppingAdmin,
            tabBarView: TabBarView(children: [
              file == null
                  ? SafeArea(
                      top: false,
                      bottom: false,
                      child: Builder(
                        builder: (BuildContext context) {
                          return CustomScrollView(
                            key: const PageStorageKey<String>(
                              TabNameString.upload,
                            ),
                            slivers: <Widget>[
                              SliverOverlapInjector(
                                handle:
                                    NestedScrollView.sliverOverlapAbsorberHandleFor(
                                  context,
                                ),
                              ),
                              SliverToBoxAdapter(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    const SizedBox(
                                      height: 60.0,
                                    ),
                                    SvgPicture.asset(
                                      ImageUrlString.uploadItemSVG,
                                      height: 260.0,
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.only(
                                        top: 20.0,
                                      ),
                                      child: ElevatedButton(
                                        onPressed: () {
                                          showDialog(
                                              context: context,
                                              builder: (context) {
                                                return BrandSimpleDialog(
                                                  dialogTitle:
                                                      DialogString.itemImage,
                                                  optionOneCallback: () async {
                                                    Navigator.pop(context);
                                                    XFile? pickedFile =
                                                        await ImagePicker()
                                                            .pickImage(
                                                      imageQuality: 85,
                                                      maxHeight: 675,
                                                      maxWidth: 960,
                                                      source: ImageSource.camera,
                                                    );
                                                    setState(() {
                                                      file = File(pickedFile!.path);
                                                    });
                                                  },
                                                  optionOneText: DialogString
                                                      .captureWithCamera,
                                                  optionTwoCallback: () async {
                                                    Navigator.pop(context);
                                                    XFile? pickedFile =
                                                        await ImagePicker()
                                                            .pickImage(
                                                      imageQuality: 85,
                                                      source: ImageSource.gallery,
                                                    );
                                                    setState(() {
                                                      file = File(pickedFile!.path);
                                                    });
                                                  },
                                                  optionTwoText: DialogString
                                                      .selectFromGallery,
                                                );
                                              });
                                        },
                                        child: Text(
                                          ButtonString.uploadNewItems.toUpperCase(),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    )
                  : UploadItemsFormPage(
                      contentImage: file as File,
                      descriptionController: descriptionController,
                      isUploading: isUploading,
                      onPressedClear: clearImage,
                      priceController: priceController,
                      titleController: titleController,
                    ),
              Container(),
              Container(),
              Container(),
            ]),
            tabs: _tabs,
          ),
        );
      }
    }