Как программно добавить элемент Text в мой виджет / класс? - PullRequest
0 голосов
/ 18 февраля 2019

У меня есть виджет, который вызывает функцию для извлечения данных из API;после завершения функции извлечения она вызывает другую функцию для создания таблицы для своего виджета.Вот код:

 import 'package:flutter/material.dart';
 import 'dart:convert';
 import 'package:http/http.dart' as http;
 void main() => runApp(MeTube());


 // class
 class MeTube extends StatefulWidget {
   @override
   State<StatefulWidget> createState() {
     return new MeTubeState();
   }
 }


 // state, component
 class MeTubeState extends State<MeTube> {
   bool _loading = true;

   @override
   Widget build(BuildContext context) {
     return MaterialApp(
       theme: ThemeData(
         // primarySwatch: Colors(212121),
       ),
       home: Scaffold(
         appBar: AppBar(
           title: Text('MeTube'),
           centerTitle: false,
           actions: <Widget>[
             IconButton(
               icon: Icon(Icons.refresh),
               onPressed: () {_fetch();},               // call the fetch function (refresh)
             )
           ],
         ),

         body: Center(
           child: _loading ? CircularProgressIndicator() : null   /* I could load the ListView here
                                                                   * and use the state to render each row
                                                                   * but if there are 1,000+ rows, that
                                                                   * would degrade the performance.
                                                                  */
         ),
       )
     );
   }


   // fetch data for the app
   _fetch() async {
     setState(() {_loading = true;});                   // start the progress indicator
     final String url = 'api.letsbuildthatapp.com/youtube/home_feed';
     final res = await http.get('https://$url');

     if (res.statusCode == 200) {                       // if successful, decode the json
       final map = json.decode(res.body);
       _build(map['videos'].length, map['videos']);     // pass the # videos, and the videos
     }
   }


   // build the data
   _build(int rows, data) {                /* MAKE EACH ROW */
     MeTube().createElement().build(       // create a ListView in the Class/Widget
       ListView.builder(
         itemCount: rows,                  /* number of rows to render, no need to setState() since this 
                                            * function (build) gets called, and the data is passed into it
                                           */

         itemBuilder: (context, index) {   // make each column for this class
           Column(children: <Widget>[
             Text(data[index]['name']),    // render some Text and a Divider in each row
             Divider()
           ]);
         },
       )
     );


     setState(() {_loading = false;});     // stop the progress indicator
   }
 }

Текущий код в функции build() довольно громоздкий и отображает ошибки.Как мне программно вставить ListView и Rows в виджет вместо того, чтобы переводить все видео в состояние, а затем запускать код для рендеринга строки из всех этих значений в состоянии?

1 Ответ

0 голосов
/ 18 февраля 2019

Конструктор ListView.builder будет создавать элементы по мере их прокрутки на экране, как по требованию.Я думаю, вам не нужно беспокоиться о производительности.Сделайте это так, как вы прокомментировали код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...