Получить значения для переменных в FutureBuilder и использовать в макете - PullRequest
0 голосов
/ 29 июня 2019

Зависимые от переменной виджеты обрабатываются до того, как FutureBuilder завершит выполнение.
Со следующим кодом 'вызвано вычитание на ноль' * появляется ошибка .
- возможно липолучить переменную word (проблема) перед созданием остальных виджетов в макете с ним?

List<int> word = [];
int length;
var rng = new Random();
  body: Column(children: [
    Container(
          child: FutureBuilder<Quote>(
            future: getQuote(), 
            builder: (BuildContext context, AsyncSnapshot<Quote> snapshot) {
              if (snapshot.hasData) {  
                word = snapshot.data.tag.runes.toList();
                word.shuffle();
                length = word.length;
                return Center(
                  child: Column(
                    children: <Widget>[
                      Text(snapshot.data.tag), 
                      Image.network(
                          '${snapshot.data.url}',
                      ), //displays the quote's author
                    ],
                  ),
                );
              } else { 
              return CircularProgressIndicator();
            },
          ),

    ),
        Container(
     height:75,
      child: GridView.count(
        crossAxisCount: 5,
        children: List.generate(5, (int index) {
          return Center(
            child:  FlatButton(
              child: Text(
                  String.fromCharCode(

Следующая строка выдает ошибку с нулевой

               index = (length-word.length)<3 ? word.removeAt(rng.nextInt(word.length))
                              : 65+rng.nextInt(25)
                  ),
...

Функция, которая загружает данные из URL

Future<Quote> getQuote() async {
var API_KEY = '12892554-73418a404928f2a4e42121633';
final object = generateNoun().take(1);
String url = "https://pixabay.com/api/? 
key="+API_KEY+"&q="+Uri.encodeFull(object.toString());
final response = await http.get(url);
if (response.statusCode == 200) {
return Quote.fromJson(json.decode(response.body));
}
}

1 Ответ

0 голосов
/ 30 июня 2019

Решено путем упаковки всего дерева макетов в FutureBuilder и помещения всего объекта в тело внутри скаффолда.

@override
Widget build(BuildContext context) {
var my_layout = FutureBuilder<Quote>(
    future: getQuote(), //sets the getQuote method as the expected Future
    builder: (BuildContext context, AsyncSnapshot<Quote> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return new Text('No preferences');
        case ConnectionState.waiting:
          return CircularProgressIndicator();
        default:
          if (snapshot.hasError) {
            return InkWell(
                child: Padding(
                  padding: const EdgeInsets.all(32.0),
                  child: Text("ERROR OCCURRED, Tap to retry !"),
                ),
                onTap: () => setState(() {}));
          }
          else { // this runs when data is retrieved properly

// set values for all variables, which depend on FutureBuilder and required in rest widgets

// put ALL widgets, that were previously in body //

return Scaffold(
  appBar: AppBar(
    title: Text('Guess word'),
  ),
  body: my_layout,
);
// close build method
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...