Сборка Flutter Future не показывает контейнер при загрузке - PullRequest
0 голосов
/ 06 мая 2020

Я пытаюсь использовать futurebuild в своем приложении, но после загрузки функции он все еще показывает индикатор загрузки, а не контейнер

Вот мой код

class _MyHomePageState extends State<MyHomePage> {
  bool showApp = false;
   var _questions = new List<Questions>();
  _getQuestions() {
    API.getUsers().then((response) {
      setState(() {

        Iterable list = json.decode(response.body);
        print(list);
        print(list);
        _questions = list.map((model) => Questions.fromJson(model)).toList();
        print(_questions);
        showApp = true;
      });
    });
  }

  int index = 0;
  bool shouldShow = false;

  @override
  Widget build(BuildContext context) {

    int size = _questions?.length;

    void nextQuestion() {
      if (index < size - 1)
        setState(() {
          index++;
        });
      print(index);
    }

    double percentage1Calculate() {
      int wouldClick = 12;
      int ratherClick = 13;
      double percentage1 = wouldClick / (wouldClick + ratherClick) * 100;
      return percentage1;
    }

    double percentage2Calculate() {
      int wouldClick = 2;
      int ratherClick = 3;
      double percentage2 = ratherClick / (wouldClick + ratherClick) * 100;
      return percentage2;
    }

    void percengtageTrigger(){
      setState(() {
        shouldShow = true;
      });
      Timer timer = Timer(Duration(milliseconds: 1350), () {
        setState(() {
          shouldShow = false;
        });
      });
    }

    final PrimaryColor = const Color(0xff404040);

    final PreferredSizeWidget appBar = AppBar(
      centerTitle: true,
      title: Text(
        'Would you Rather',
        style: TextStyle(fontFamily: 'FredokaOne'),
      ),
      backgroundColor: PrimaryColor,
    );
    double stackHeight = (MediaQuery.of(context).size.height -
        appBar.preferredSize.height -
        MediaQuery.of(context).padding.top);
    double stackWidth = MediaQuery.of(context).size.width;
    return FutureBuilder(


        initialData:null, //initial default data if you have some
        future: _getQuestions(),
        builder:(BuildContext context, AsyncSnapshot<String> snapshot){
           if(snapshot.hasData){
             print("Data found, You can continue");
             return Center(
               child: Container(
                 child: Text('data avail'),

               ),
             );
           }
           else if (snapshot.hasError) {
             return Center(
               child: Container(
                 child: Text('error'),

               ),
             );
           }
           else{
             print("loading");
             return CircularProgressIndicator();
           }
        }
    );
  }
}

Я использую _getQuestions в будущее, но он просто печатает значение функции. Не отображается контейнер snapshot.hasData

Не знаю, почему функция печатает данные, но в FutureBuilder его состояние не меняется :(

Типовой вопрос

import 'package:flutter/material.dart';


class Questions {
  String would;
  String rather;
  int wouldClick;
  int ratherClick;

  Questions(int wouldClick, int ratherClick, String would, String rather) {
    this.wouldClick = wouldClick;
    this.ratherClick = ratherClick;
    this.would = would;
    this.rather = rather;
  }

  Questions.fromJson(Map json)
      : wouldClick = json['wouldClick'],
        ratherClick = json['ratherClick'],
        would = json['would'],
        rather = json['rather'];

  Map toJson() {
    return {'wouldClick': wouldClick, 'ratherClick': ratherClick, 'would': would, 'rather': rather};
  }
  @override
  String toString() {
    return "{would: $would, rather: $rather, wouldClick: $wouldClick, ratherClick: $ratherClick}";
  }
}

1 Ответ

1 голос
/ 06 мая 2020

используйте это:

class _MyHomePageState extends State<MyHomePage> {
  bool showApp = false;
  Future myQuestionsFuture;

  var _questions = new List<Questions>();

  @override
  void initState() {
    myQuestionsFuture = _getQuestions();
    super.initState();
  }

  Future<List<Questions>> _getQuestions() async {
    final response = await API.getUsers();
    Iterable list = json.decode(response.body);
    print(list);
    print(list);
    _questions = list.map((model) => Questions.fromJson(model)).toList();
    print(_questions);
    setState(() {
      showApp = true;
    });
    return _questions;
  }

  int index = 0;
  bool shouldShow = false;

  @override
  Widget build(BuildContext context) {
    int size = _questions?.length;

    void nextQuestion() {
      if (index < size - 1)
        setState(() {
          index++;
        });
      print(index);
    }

    double percentage1Calculate() {
      int wouldClick = 12;
      int ratherClick = 13;
      double percentage1 = wouldClick / (wouldClick + ratherClick) * 100;
      return percentage1;
    }

    double percentage2Calculate() {
      int wouldClick = 2;
      int ratherClick = 3;
      double percentage2 = ratherClick / (wouldClick + ratherClick) * 100;
      return percentage2;
    }

    void percengtageTrigger() {
      setState(() {
        shouldShow = true;
      });
      Timer timer = Timer(Duration(milliseconds: 1350), () {
        setState(() {
          shouldShow = false;
        });
      });
    }

    final PrimaryColor = const Color(0xff404040);

    final PreferredSizeWidget appBar = AppBar(
      centerTitle: true,
      title: Text(
        'Would you Rather',
        style: TextStyle(fontFamily: 'FredokaOne'),
      ),
      backgroundColor: PrimaryColor,
    );
    double stackHeight = (MediaQuery.of(context).size.height -
        appBar.preferredSize.height -
        MediaQuery.of(context).padding.top);
    double stackWidth = MediaQuery.of(context).size.width;
    return FutureBuilder<List<Questions>>(
        initialData: null, //initial default data if you have some
        future:myQuestionsFuture,
        builder: (BuildContext context, AsyncSnapshot<List<Questions>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              print("Data found, You can continue");
              return Center(
                child: Container(
                  child: Text('data avail'),
                ),
              );
            } else if (snapshot.hasError) {
              return Center(
                child: Container(
                  child: Text('error'),
                ),
              );
            }
          } else {
            print("loading");
            return CircularProgressIndicator();
          }
        });
  }
}
...