dart 自< dynamic>定义滚动视图抖动内部的FutureBuilder

xcitsw88  于 2023-03-15  发布在  其他
关注(0)|答案(3)|浏览(135)

嗨,我想设计一个页面,应该垂直滚动,应该有GridView.builder。我击中服务器加载数据,如果数据是在共享首选项,然后我从共享首选项中获得它。对于GridView.builder,我使用FutureBuilder加载数据。但我得到以下错误
“所有者._调试当前生成目标==此”:不是真的

下面是代码。

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // Initialize without device test ids
  Admob.initialize();
  // Add a list of test ids.
  // Admob.initialize(testDeviceIds: ['YOUR DEVICE ID']);

  runApp(FirstScreen());
}

class FirstScreen extends StatefulWidget {
  @override
  _CrosspromoPageState createState() => _CrosspromoPageState();
}

class _CrosspromoPageState extends State<FirstScreen> {
  AdmobInterstitial interstitialAd;
  List<CrosspromotionPojo> crosspromoobject = List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // getCrosspromodata();
    // loadcrossPromodata();
    interstitialAd = AdmobInterstitial(
      adUnitId: getInterstitialAdUnitId(),
      listener: (AdmobAdEvent event, Map<String, dynamic> args) {
        if (event == AdmobAdEvent.closed) interstitialAd.load();
      },
    );
    interstitialAd.load();
  }

  String getInterstitialAdUnitId() {
    if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/4411468910';
    } else if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/1033173712';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    SizeConfig().init(context);
    return Scaffold(
      body: Container(
        child: CustomScrollView(
          slivers: <Widget>[
            new Image.asset('assets/images/bg_half_image.jpg'),
            new Align(
                alignment: Alignment.topCenter,
                child: new Container(
                  margin: EdgeInsets.fromLTRB(0, 55, 0, 0),
                  width: 150,
                  height: 150,
                  child: Image.asset('assets/images/logo.png'),
                )),
            new Align(
                alignment: Alignment.topCenter,
                child: InkWell(
                    onTap: () async {
                      if (await interstitialAd.isLoaded) {
                        interstitialAd.show();
                      }
                      int val = await DatabaseHelper.instance.queryRowCount();
                      if (val == 0) {
                        DatabaseHelper.instance.insertExcdaydata();
                        DatabaseHelper.instance.insertExcdaydatainapp();
                      } else
                        Navigator.pop(context, true);
                      {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => BannerPage(),
                          ),
                        );
                      }
                    },
                    child: new Container(
                      width: 150,
                      margin: EdgeInsets.fromLTRB(0, 200, 0, 0),
                      //padding: EdgeInsets.fromLTRB(4, 0, 4, 4),
                      child: new Image.asset('assets/images/start.png'),
                    ))),
            new Container(
              alignment: Alignment.topCenter,
              margin: EdgeInsets.only(
                  left: 0,
                  right: 0,
                  top: SizeConfig.screenHeight / 1.8,
                  bottom: 0),
              child: Text("TRY OUR NEW APPS",
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 20)),
            ),
            new FutureBuilder<dynamic>(
                future: getCrosspromodata(),
                builder:
                    (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Center(child: Text('Please wait its loading...'));
                  } else {
                    return Container(
                      margin: EdgeInsets.only(
                          left: 0,
                          right: 0,
                          top: SizeConfig.screenHeight / 1.6,
                          bottom: 0),
                      child: Align(
                        child: GridView.builder(
                          itemCount: crosspromoobject.length,
                          itemBuilder: (context, index) => GestureDetector(
                            onTap: () => tapped(index),
                            child: Container(
                                child: new Card(
                              elevation: 2,
                              child: Column(
                                children: <Widget>[
                                  new Container(
                                    child: CachedNetworkImage(
                                      imageUrl: crosspromoobject[index].appUrl,
                                      placeholder: (context, url) =>
                                          CircularProgressIndicator(),
                                      errorWidget: (context, url, error) =>
                                          Icon(Icons.error),
                                    ),
                                  ),
                                  new Container(
                                      alignment:
                                          AlignmentDirectional.centerStart,
                                      child: Text(
                                        crosspromoobject[index].app_name,
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 15),
                                      ))
                                ],
                              ),
                            )),
                          ),
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3,
                            mainAxisSpacing: 30,
                            crossAxisSpacing: 15,
                            childAspectRatio:
                                MediaQuery.of(context).size.width /
                                    (MediaQuery.of(context).size.height / 1.1),
                          ),
                        ),
                      ),
                    );
                  }
                })
          ],
        ),
      ),
    );
    /*return Scaffold(
        body: Scaffold(
            body: Stack(
      children: [
        new Image.asset('assets/images/bg_half_image.jpg'),
        new Align(
            alignment: Alignment.topCenter,
            child: new Container(
              margin: EdgeInsets.fromLTRB(0, 55, 0, 0),
              width: 150,
              height: 150,
              child: Image.asset('assets/images/logo.png'),
            )),
        new Align(
            alignment: Alignment.topCenter,
            child: InkWell(
                onTap: () async {
                  if (await interstitialAd.isLoaded) {
                    interstitialAd.show();
                  }
                  int val = await DatabaseHelper.instance.queryRowCount();
                  if (val == 0) {
                    DatabaseHelper.instance.insertExcdaydata();
                    DatabaseHelper.instance.insertExcdaydatainapp();
                  } else
                    Navigator.pop(context, true);
                  {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => BannerPage(),
                      ),
                    );
                  }
                },
                child: new Container(
                  width: 150,
                  margin: EdgeInsets.fromLTRB(0, 200, 0, 0),
                  //padding: EdgeInsets.fromLTRB(4, 0, 4, 4),
                  child: new Image.asset('assets/images/start.png'),
                ))),
        new Container(
          alignment: Alignment.topCenter,
          margin: EdgeInsets.only(
              left: 0, right: 0, top: SizeConfig.screenHeight / 1.8, bottom: 0),
          child: Text("TRY OUR NEW APPS",
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                  fontSize: 20)),
        ),
        new FutureBuilder<dynamic>(
            future: getCrosspromodata(),
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(child: Text('Please wait its loading...'));
              } else {
                return Container(
                  margin: EdgeInsets.only(
                      left: 0,
                      right: 0,
                      top: SizeConfig.screenHeight / 1.6,
                      bottom: 0),
                  child: Align(
                    child: GridView.builder(
                      itemCount: crosspromoobject.length,
                      itemBuilder: (context, index) => GestureDetector(
                        onTap: () => tapped(index),
                        child: Container(
                            child: new Card(
                          elevation: 2,
                          child: Column(
                            children: <Widget>[
                              new Container(
                                child: CachedNetworkImage(
                                  imageUrl: crosspromoobject[index].appUrl,
                                  placeholder: (context, url) =>
                                      CircularProgressIndicator(),
                                  errorWidget: (context, url, error) =>
                                      Icon(Icons.error),
                                ),
                              ),
                              new Container(
                                alignment: AlignmentDirectional.centerStart,
                                  child: Text(
                                crosspromoobject[index].app_name,
                                style: TextStyle(
                                    color: Colors.black, fontSize: 15),
                              ))
                            ],
                          ),
                        )),
                      ),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        mainAxisSpacing: 30,
                        crossAxisSpacing: 15,
                        childAspectRatio: MediaQuery.of(context).size.width /
                            (MediaQuery.of(context).size.height / 1.1),
                      ),
                    ),
                  ),
                );
              }
            })
      ],
    )))*/
  }

  Future<dynamic> loadcrossPromodata() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    List<dynamic> tagObjsJson =
        (json.decode(pref.getString('userData')) ?? List<dynamic>());
    crosspromoobject = tagObjsJson
        .map((tagJson) => CrosspromotionPojo.fromJson(tagJson))
        .toList();
    return tagObjsJson;
  }

  Future<dynamic> getCrosspromodata() async {
    List<dynamic> tagObjsJson;
    SharedPreferences pref = await SharedPreferences.getInstance();
    try {
      Response<Map> versionresponse = await Dio().get(
          "https://videomergerapp.com/mobilestores/https/cross_promo_photoapps/verison.json");
      Map arrayObjresponse = versionresponse.data;
      int version = arrayObjresponse['healthw_version'];
      int localversion = pref.getInt('local_version') ?? 0;
      if (version > localversion) {
        Response<Map> response = await Dio().get(
            "https://videomergerapp.com/mobilestores/https/cross_promo_fitness/cross_promo_health_fitness_firstscreen.json");
        String arrayObjsText = response.toString();
        tagObjsJson = jsonDecode(arrayObjsText)['item_array'] as List;
        crosspromoobject = tagObjsJson
            .map((tagJson) => CrosspromotionPojo.fromJson(tagJson))
            .toList();
        savePojo(tagObjsJson);
        pref.setInt('local_version', version);
        return tagObjsJson;
      } else {
        loadcrossPromodata();
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> savePojo(List<dynamic> crosspromoobject) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setString('userData', json.encode(crosspromoobject));
    print(crosspromoobject);
  }

  void tapped(int index) {
    Fluttertoast.showToast(
        msg: crosspromoobject[index].app_name,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
wr98u20j

wr98u20j1#

尝试将GridView的属性shrinkWrap设置为true

GridView.builder(
   shrinkWrap: true,
   //...
)
f0brbegy

f0brbegy2#

因此,我将SliverList和SliverChildListDelegate放入CustomScrollView中,并在FutureBuilder height中为容器赋予高度:SizeConfig.screenHeight / 1.10,下面是完整的代码.

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // Initialize without device test ids
  Admob.initialize();
  // Add a list of test ids.
  // Admob.initialize(testDeviceIds: ['YOUR DEVICE ID']);

  runApp(FirstScreen());
}

class FirstScreen extends StatefulWidget {
  @override
  _CrosspromoPageState createState() => _CrosspromoPageState();
}

class _CrosspromoPageState extends State<FirstScreen> {
  AdmobInterstitial interstitialAd;
  List<CrosspromotionPojo> crosspromoobject = List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // getCrosspromodata();
    // loadcrossPromodata();
 
  }

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    SizeConfig().init(context);
    return Scaffold(
        body: Container(
            child: CustomScrollView(slivers: <Widget>[
      SliverList(
          delegate: SliverChildListDelegate(
        [
          Stack(
            children: [
              new Image.asset('assets/images/bg_half_image.jpg'),
              new Align(
                  alignment: Alignment.topCenter,
                  child: new Container(
                    margin: EdgeInsets.fromLTRB(0, 55, 0, 0),
                    width: 150,
                    height: 150,
                    child: Image.asset('assets/images/logo.png'),
                  )),
              new Align(
                  alignment: Alignment.topCenter,
                  child: InkWell(
                      onTap: () async {
                        if (await interstitialAd.isLoaded) {
                          interstitialAd.show();
                        }
                        int val = await DatabaseHelper.instance.queryRowCount();
                        if (val == 0) {
                          DatabaseHelper.instance.insertExcdaydata();
                          DatabaseHelper.instance.insertExcdaydatainapp();
                        } else
                          Navigator.pop(context, true);
                        {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => BannerPage(),
                            ),
                          );
                        }
                      },
                      child: new Container(
                        width: 150,
                        margin: EdgeInsets.fromLTRB(0, 200, 0, 0),
                        //padding: EdgeInsets.fromLTRB(4, 0, 4, 4),
                        child: new Image.asset('assets/images/start.png'),
                      )))
            ],
          ),
          new SizedBox(
            height: 50,
            width: double.infinity,
            child: Container(
              margin: EdgeInsets.fromLTRB(0, 15, 0, 0),
              color: Colors.white,
              child: Text(
                "TRY OUR NEW APPS",
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                    fontSize: 20),
              ),
            ),
          ),
          new FutureBuilder<dynamic>(
              future: getCrosspromodata(),
              builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: Text('Please wait its loading...'));
                } else {
                  return Container(
                    height: SizeConfig.screenHeight / 1.10,
                    margin:
                        EdgeInsets.only(left: 0, right: 0, top: 0, bottom: 0),
                    child: Align(
                      child: GridView.builder(
                        itemCount: crosspromoobject.length,
                        itemBuilder: (context, index) => GestureDetector(
                          onTap: () => tapped(index),
                          child: Container(
                              child: new Card(
                            elevation: 2,
                            child: Column(
                              children: <Widget>[
                                new Container(
                                  child: CachedNetworkImage(
                                    imageUrl: crosspromoobject[index].appUrl,
                                    placeholder: (context, url) =>
                                        CircularProgressIndicator(),
                                    errorWidget: (context, url, error) =>
                                        Icon(Icons.error),
                                  ),
                                ),
                                new Container(
                                    alignment: AlignmentDirectional.centerStart,
                                    child: Text(
                                      crosspromoobject[index].app_name,
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 15),
                                    ))
                              ],
                            ),
                          )),
                        ),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          mainAxisSpacing: 30,
                          crossAxisSpacing: 15,
                          childAspectRatio: MediaQuery.of(context).size.width /
                              (MediaQuery.of(context).size.height / 1.1),
                        ),
                      ),
                    ),
                  );
                }
              })
        ],
      )),
    ]))
        // This trailing comma makes auto-formatting nicer for build methods.
        );
  }

  Future<String> loadcrossPromodata() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    List<dynamic> tagObjsJson =
        (json.decode(pref.getString('userData')) ?? List<dynamic>());
    crosspromoobject = tagObjsJson
        .map((tagJson) => CrosspromotionPojo.fromJson(tagJson))
        .toList();
  }

  Future<dynamic> getCrosspromodata() async {
    List<dynamic> tagObjsJson;
    SharedPreferences pref = await SharedPreferences.getInstance();
    try {
      Response<Map> versionresponse = await Dio().get(
          "https://videomergerapp.com/mobilestores/https/cross_promo_photoapps/verison.json");
      Map arrayObjresponse = versionresponse.data;
      int version = arrayObjresponse['healthw_version'];
      int localversion = pref.getInt('local_version') ?? 0;
      if (version > localversion) {
        Response<Map> response = await Dio().get(
            "https://videomergerapp.com/mobilestores/https/cross_promo_fitness/cross_promo_health_fitness_firstscreen.json");
        String arrayObjsText = response.toString();
        tagObjsJson = jsonDecode(arrayObjsText)['item_array'] as List;
        crosspromoobject = tagObjsJson
            .map((tagJson) => CrosspromotionPojo.fromJson(tagJson))
            .toList();
        savePojo(tagObjsJson);
        pref.setInt('local_version', version);
        return tagObjsJson;
      } else {
        loadcrossPromodata();
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> savePojo(List<dynamic> crosspromoobject) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setString('userData', json.encode(crosspromoobject));
    print(crosspromoobject);
  }

  void tapped(int index) {
    Fluttertoast.showToast(
        msg: crosspromoobject[index].app_name,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
c8ib6hqw

c8ib6hqw3#

始终确保CustomScrollView的子级实际上是 slivers。这意味着,如果它们不是,您应该将它们 Package 在例如SliverToBoxAdapter中。
所以不要写这样的东西:

CustomScrollView(                
  slivers: [                     
    Image.asset('path/to/image'),
    Text("Example text"),        
  ],                             
)

将其编辑为:

CustomScrollView(                                           
  slivers: [                                                
    SliverToBoxAdapter(child: Image.asset('path/to/image')),
    SliverToBoxAdapter(child: Text("Example text")),        
  ],                                                        
)

相关问题