Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

Passing data from parent to child StatefulWidget Flutter

Hellow, Im newbie in flutter..please help me to pass data from parent to child statefullwidget.. then..send to API..

This is my code

class Home extends StatefulWidget {
  final String user; // I will passing this into getCategory()
  final String email;

  Home(this.user, this.email);

  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  CategoryList listCategory = CategoryList();

  void getCategory() async {
    var json = await ApiCategoryList().getCategoryList(widget.user); //not working ..
    setState(() {
      listCategory = CategoryList.fromJson(json);
    });
  }

  @override
  void initState() {
    super.initState();
    this.getCategory();
  }

@override
  Widget build(BuildContext context) {
   return ListTile(data from API here)
}

Thanks for helping me..regards


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem has nothing to do with passing the data to the child widget. Except that you probably can't call the values from initState. The problem is you are accessing it probably before it is loaded.

To solve this there is a Widget called FutureBuilder. Here is how to use it:

instead of return ListTile(data from API here) use

return FutureBuilder(
      future: getCategory(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return //Here the listTile
        }
          return //Here what should be displayed while loading
                 //I would recommend CircularProgressIndicator();
        }
)

The Futurebuilder executes a function and waits until it is finished, then it builds the desired widgets. For this to work, the getCategory function must be edited. Since the function is now called from the FutureBuider, you may no longer execute it from the initState.

  CategoryList listCategory = CategoryList(); //Delete

  Future<CategoryList> getCategory() async {
    CategoryList listCategory = CategoryList();
    // Get data from api:
    // ....

    //pass data to listCatergory:
    listCategory = CategoryList.fromJson(json);
    
    // return
    return listCategory 
   
  }

When you will acces data in the FutureBuilder you will have to use:

snapshot.theDataYouWant

e.g.

Text(
 snapshot.theDataYouWant
),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...