Flutter динамически устанавливает детей

Поэтому я хочу динамически устанавливать дочерние элементы моего GridView, чтобы я мог устанавливать их, когда захочу. На данный момент это весь класс.

import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/CustomColors.dart';
import 'package:flutter_app/quote/Quote.dart';
import 'package:flutter_app/quote/QuoteView.dart';
import 'package:flutter_app/section/Section.dart';
import 'package:flutter_app/quote/QuoteData.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  static List<QuoteData> data = [];

  _readJson() async {
    data.clear();
    var url = 'https://www.dropbox.com/s/7k280ca5dktlhoo/quotes.json?dl=1';
    var httpClient = new HttpClient();
    httpClient.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
      return request.close();
    }).then((HttpClientResponse response) {
      response.transform(utf8.decoder).listen((contents) {
        List<Map> decoded = JSON.decode(contents);
        decoded.forEach((m) {
          String url = m["url"];
          String title = m["title"];
          String sectionString = m["section"];
          Section section;
          for (Section element in Section.values) {
            if (element.toString() == "Section." + sectionString) {
              section = element;
            }
          }
          List<Quote> quotes = m["quotes"];
          data.add(new QuoteData(url, title, section, quotes));
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    _readJson();
    return new MaterialApp(
      title: 'Quotes',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: CustomColors.black,
      ),
      home: new MyHomePage(title: 'Quotes'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  static Section currentSection = Section.movies;

  void _onTileClicked(QuoteData quote) {
    Navigator.push(context,
        new MaterialPageRoute(builder: (context) => new QuoteView(quote)));
  }

  List<Widget> _getTiles(Section section) {
    final List<Widget> tiles = <Widget>[];
    for (var i in MyApp.data) {
      if (i.section != section) {
        continue;
      }
      tiles.add(new GridTile(
          child: new InkResponse(
        enableFeedback: true,
        child: new Image.network(
          i.url,
          fit: BoxFit.cover,
        ),
        onTap: () => _onTileClicked(i),
      )));
    }
    return tiles;
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
    final double itemWidth = size.width / 2;
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text(currentSection
                .toString()
                .replaceAll("Section.", "")
                .substring(0, 1)
                .toUpperCase() +
            currentSection.toString().replaceAll("Section.", "").substring(1)),
      ),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new GridView.count(
            crossAxisCount: 2,
            childAspectRatio: (itemWidth / itemHeight),
            padding: const EdgeInsets.all(4.0),
            mainAxisSpacing: 4.0,
            crossAxisSpacing: 4.0,
            children: _getTiles(currentSection)),
      ),
    );
  }
}

Итак, прямо сейчас при запуске он запускает приложение, но MyApp.data пуст, потому что должен быть прочитан json, поэтому GridView будет пустым, когда я обновляю приложение, GridView не будет пустым, потому что MyApp.data не будет больше быть пустым. Я хочу иметь возможность устанавливать дочерние элементы после того, как json будет прочитан, также мне нужно иметь возможность изменять его динамически, потому что я добавлю функцию для переключения разделов.

То же самое и с заголовком, мне также нужно иметь возможность динамически изменять его при переключении разделов.

Вы можете использовать docs.flutter.io/flutter/widgets/FutureBuilder-class.html. Если у вас уже есть значения, вы можете вернуть их с помощью new Future.value(myData) или, если вы получите или загрузите данные из метода, помеченного как async, вы всегда получите обратно Future.

Günter Zöchbauer 30.03.2018 13:09

Я не могу использовать FutureBuilder в GridView

Kiraged 30.03.2018 13:21

Почему нет? Вы можете обернуть свой GridView в FutureBuilder

Günter Zöchbauer 30.03.2018 13:22

Спасибо, я получил эту часть, но я не совсем понимаю, что вы имеете в виду в последнем предложении, где вы получаете Future обратно в асинхронном методе.

Kiraged 30.03.2018 13:35

Я сам еще не пробовал FutureBuilder (: D), но предполагаю, что он ожидает Future. Если вы получите данные с сервера, у вас будет Future автоматически, но позже, когда у вас уже есть данные и они понадобятся как Future, вы можете использовать Future.value(data), но возможно, что FutureBuilder все равно не заботится и распознает, является ли это Future или нет.

Günter Zöchbauer 30.03.2018 13:37

Future.value ожидает значение FutureOr <T>, поэтому, когда я помещаю MyApp.data, который является списком, он не сработает. На данный момент у меня есть этот hastebin.com/upodojivam.cs

Kiraged 30.03.2018 13:42
FutureOr<T> предназначен для приема T (не для будущего) или Future<T>, который является Future. Какая у вас ошибка?
Günter Zöchbauer 30.03.2018 13:47

Future.value хочет FutureOr <T>, но MyApp.data - это List <T>, поэтому я не могу его использовать.

Kiraged 30.03.2018 13:51

Какое сообщение об ошибке вы получаете? T - это просто имя параметра. Попробуйте new Future<dynamic>.value(MyApp.data)

Günter Zöchbauer 30.03.2018 13:53

Позвольте нам продолжить обсуждение в чате.

Kiraged 30.03.2018 13:54

Извини, что пришлось уйти. Каков текущий статус?

Günter Zöchbauer 30.03.2018 16:50

Больше ничего не получил, это код hastebin.com/opelewayus.scala при запуске debugPrint («Да»); вызывается, но debugPrint ("Да 1"); нет. Если я обновлю приложение, оба будут вызваны.

Kiraged 30.03.2018 21:46
0
12
3 854
1

Ответы 1

Вы можете создать виджет загрузки и дождаться завершения запроса, когда запрос будет завершен, скрыть загрузку и показать сетку, чем перестроить состояние. но вам нужно иметь statefullWidget, а не statelessWidget.

Вы можете увидеть, как я его использую, в приведенном ниже коде. Я добавил свои комментарии к коду.

class _ChildrenPageState extends State<ChildrenPage>  {
  //declare the _load to true so it will show the loading when the page is loaded
  bool _load = true;
  ChildrenService _childrenService = new ChildrenService();
  List children = [];

  //I call the _rebuild function to rebuild the widgets and show the data
  void _rebuild() {
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    //I call the request to get my data when it is finished i put _load to false so the loading will hide and call the _rebuild function to rebuild the widgets and i have put if so when the widget is built it will not rebuild it a second time.

    _childrenService.getChildren(children).then((data){
      if (data && _load){
        _load = false;
        _rebuild();
      }
    });

    //the below widget show the loading container if _load is true else it will show the dataTable in your app you should add the grid and you can pass the data that you got from the request

    Widget loadingIndicator = _load ? new Container(
      color: Colors.grey[300],
      width: 70.0,
      height: 70.0,
      child: new Padding(
          padding: const EdgeInsets.all(5.0),
          child: new Center(
              child: new CircularProgressIndicator()
          )
      ),
    ) : new JLDataTable(
      data: children,
    );

    return new Scaffold(
        drawer: new Drawer(
          child: MenuList.menuList,
        ),
        appBar: new AppBar(title: const Text('Data tables')),
        body: new ListView(
            padding: const EdgeInsets.all(20.0),
            children: <Widget>[
                new Align(
                    child: loadingIndicator,
                    alignment: FractionalOffset.center
                )
            ]
        )
    );
  }
}

Спасибо за вашу помощь, но я решил отказаться от флаттера. Я мог бы попробовать еще раз, если у вас есть доступ к представлениям через код.

Kiraged 01.04.2018 11:06

Другие вопросы по теме