Future <void>返回小部件构建多次

时间:2020-06-22 05:57:52

标签: flutter dart

在我的代码中,我尝试从Firebase实时数据库中获取数据,并将其填充到我的Widget中,但是直到再次重新加载该应用程序后,我才能看到这些数据。因此,我尝试打印“硬编码”值,并且能够看到数据在屏幕上弹出两次,这可能是由于多次构建所致。我经历了多种解决方案,但无法解决。

这是我的代码:

class CategoryHomeScreen extends StatefulWidget {
  @override
  _CategoryHomeScreenState createState() => _CategoryHomeScreenState();
}

class _CategoryHomeScreenState extends State<CategoryHomeScreen> {

//  List<CategoriesOnly> categoriesOnlyList =[];
//  List<CategoryItems> categoryItemList = [];

  List<CategoriesOnly> categoriesOnlyList = List();
  List<CategoryItems> categoryItemList = List();
  CategoryItems categoryItems;
  CategoriesOnly categoriesOnly;
  DatabaseReference itemRef,nameRef;



@override
void initState() {
    // TODO: implement initState
    getCategoriesName();
    super.initState();


  }
  Future<void> getCategoriesName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var userPin = prefs.getString('pin');

    var CategoryName =  FirebaseDatabase.instance.reference().child('CategoryNames').child(userPin).once()
        .then((DataSnapshot dataSnapshot){
      var key  = dataSnapshot.value.keys;
      for(var i in key)
      {
       // print(dataSnapshot.value[i]['Name']);
        CategoriesOnly categoriesOnly = new CategoriesOnly(
            dataSnapshot.value[i]['Name']
        );
        categoriesOnlyList.add(categoriesOnly);
      }

    });

    var categoryItemDetails =  FirebaseDatabase.instance.reference().child('Categories').child(userPin).once()
        .then((DataSnapshot dataSnapshot){
      var key  = dataSnapshot.value.keys;
      for(var i in key)
      {
        CategoryItems categoryItems = new CategoryItems(
            dataSnapshot.value[i]['CategoryName'],
            dataSnapshot.value[i]['MarketPrice'],
            dataSnapshot.value[i]['Name'],
            dataSnapshot.value[i]['OurPrice'],
            dataSnapshot.value[i]['TotalDiscount'],
            dataSnapshot.value[i]['Weight']

        );
        categoryItemList.add(categoryItems);
      }

    });
  }

  @override
  Widget build(BuildContext context) {
//    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
//      statusBarColor: Colors.black, //or set color with: Color(0xFF0000FF)
//    ));
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Container(
          child: UI(),
        ),
      )
    );
  }
  Widget UI(){
  return Text('Hello World',style: TextStyle(color: Colors.white),);
  }

}

1 个答案:

答案 0 :(得分:0)

我尝试使其尽可能地易于阅读。该代码段如下所示:

import 'package:flutter/material.dart';

class bla extends StatefulWidget {
  bla({Key key}) : super(key: key);

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

class _blaState extends State<bla> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: YourApiFunction(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            return BuildYourWidgetFunction(snapshot.data);
          } else {
            return CircularProgressIndicator();
          }
        },
      ),
    );
  }

  Widget BuildYourWidgetFunction(dynamic data) {
    // build your widget here
    return Container();
  }

  Future<List<YourItem>> YourApiFunction() async {
    // your firebase / any api call here
    return await YourApiCall();
  }
}