简体   繁体   中英

Flutter: How to extract arguments which comes from another widget in a StatefulWidget?

i'm trying to extract the ModalRoute as a Global value in a StatefulWidget but it's not working, i can extract it locally under Widget build(BuildContext context) and it will work but the Global methods and widgets that i'm working on wont work, please help:'(

Here is my code,

it starts from here:

home.dart

 GestureDetector(
                              onTap: ()async{
                               await Navigator.of(context).pushNamed(MainTankHomePage.routeName, arguments: widget.tankID);
//widget.tankID is a String and i extracted it in MainTankHomePage.dart with ModalRoute as a String it works perfectly so no need to change anything here
                              },

MainTankHomePage.dart

import 'package:flutter/material.dart';
import 'package:animations/animations.dart';
import 'package:smart_tank1/main_tank_detail_ui/home/bottom_nav_bar.dart';
import 'package:smart_tank1/main_tank_detail_ui/hydration_pool/hydration_pool_page.dart';
import 'package:smart_tank1/main_tank_detail_ui/hydration_progress/hydration_progress_page.dart';
import 'package:smart_tank1/main_tank_detail_ui/summary/summary_page.dart';



class MainTankHomePage extends StatefulWidget {
  static const routeName = 'main-screen';
  @override
  _MainTankHomePageState createState() => _MainTankHomePageState();
}
class _MainTankHomePageState extends State<MainTankHomePage> {

//------------------------------------------
//Here is my global methods that i worked on
//------------------------------------------

  late final tanksID = ModalRoute.of(context)!.settings.arguments as String; // added late to get the (context) work without error line but it didn't work
  
  final _pages = <Widget>[
//----------------------------------------
//Here is the problem that i'm facing!
//Done all of the parameters work in each widget with a required tankID
//So what i need here is just passing the extracted ModalRoute here which is the tanksID to each widget but it's not working
//-----------------------------------------
        MainTankHydrationPoolPage(tankID: tanksID,),
        MainHydrationProgressPage(tankID: tanksID,),
        SummaryPage(tanksID: tanksID),
//-----------------------------
//Here is the error i get
//String tanksID
//package:smart_tank1/main_tank_detail_ui/home/main_tank_home_page.dart

//The instance member 'tanksID' can't be accessed in an initializer.
//Try replacing the reference to the instance member with a different //expression
//-------------------------------
      ];
    
    int _currentPage = 0;

    void _changePage(int index) {
      if (index == _currentPage) return;

      setState(() {
        _currentPage = index;
      });
    }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          PageTransitionSwitcher(
            transitionBuilder: (
              child,
              primaryAnimation,
              secondaryAnimation,
            ) {
              return FadeThroughTransition(
                fillColor: Theme.of(context).backgroundColor,
                animation: primaryAnimation,
                secondaryAnimation: secondaryAnimation,
                child: child,
              );
            },
            child: _pages[_currentPage],
          ),
          BottomNavBar(
            currentPage: _currentPage,
            onChanged: _changePage,
          ),
        ],
      ),
    );
  }
}

It is possible to get null value from ModalRoute , I will suggest using nullable data.

late final String? tanksID = ModalRoute.of(context)?.settings.arguments as String?; 

And pass default value while it gets null

MainTankHydrationPoolPage(tankID: tanksID??"default id",),

Or ignore build

if(tanksID!=null)  MainTankHydrationPoolPage(tankID: tanksID!,),

Make sure checking null before using ! .

  late List<Widget> _pages;

  @override
  void initState() {
    _pages = [
     .....,
    ];
    super.initState();
  }

Check more about null-safety and check this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM