颤振循环

Flutter For Loop

你好学习 Flutter,我正在尝试将这个 for 循环从 Appcelerator 转移到 Flutter。

Appcelerator:
    Alloy.Globals.networkRequest.send({
        url : Alloy.Globals.networkConfigs.albums_url,
        method : "GET",
        payload : null,
        success : function(e_response) {
            jsonResponse = JSON.parse(e_response);
            var currentIndex = 0;
            var counter = 1;

            var parsedArray = [];

            Ti.API.info('===ALBUMS_URL JSON RESPONSE==== ' + JSON.stringify(jsonResponse));
            Ti.App.Properties.setObject("ALBUMS", jsonResponse);

            for (var i = 0,
                j = jsonResponse.length; i < j; i++) {
                if (i <= 21) {

                    var views_received = Alloy.createController('view_new_release', {
                        title : jsonResponse[i].title,
                        recordID : jsonResponse[i].id,
                        song : jsonResponse[i].list_items,
                        tracksData : jsonResponse[i],
                        coverImage : jsonResponse[i].cover_url, // 
                        callback : function(data) {

                            $.global_player.loadGloabalPlayerData($.view_parent_customer_selection);

                            Ti.API.info('====view_new_release click data====== ' + JSON.stringify(data));

在 Flutter 上,我只是抓取数据并按顺序显示它,但我想添加 for 循环,以便我更好地关注数据。这是我试图更改的关于 Flutter 的代码。如果有人可以提供帮助,我将不胜感激。谢谢

Container(
                height: MediaQuery.of(context).size.height * 0.25,
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                child: ListView.builder(
                    shrinkWrap: true,
                    scrollDirection: Axis.horizontal,
                    itemCount: distributions == null ? 0 : distributions.length,
                    itemBuilder: (BuildContext context, int i) {
                      if (distributions == null) {
                        return Center(
                          child: CircularProgressIndicator(),
                        );
                      } else {
                        return Padding(
                          padding: const EdgeInsets.all(5.0),
                          child: Column(
                            children: <Widget>[
                              Container(
                                child: Center(
                                  child: GestureDetector(
                                    onTap: () {
                                      playMySong(
                                          distributions[i]['list_items']['0']
                                              ['title'],
                                          distributions[i]['list_items']['0']
                                              ['artist'],
                                          distributions[i]['list_items']['0']
                                              ['genre'],
                                          distributions[i]['list_items']['0']
                                              ['song'],
                                          distributions[i]['list_items']['0']
                                              ['lyrics'],
                                          distributions[i]['cover_url']);
                                      print(distributions[i]['list_items']['0']
                                          ['song']);
                                    },
                                    child: CachedNetworkImage(
                                      imageUrl: distributions[i]['cover_url']
                                          .toString(),
                                      fit: BoxFit.fitHeight,
                                      placeholder: (context, url) =>
                                          CircularProgressIndicator(),
                                      errorWidget: (context, url, error) =>
                                          Icon(Icons.error),
                                    ),
                                  ),
                                ),
                                width: MediaQuery.of(context).size.width * 0.3,
                                decoration: BoxDecoration(
                                  color: Colors.grey[850],
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(5)),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(5.0),
                                child: Text(
                                  distributions[i]['title'].toString(),
                                  // titles[i],
                                  style: TextStyle(
                                    color: Colors.white,
                                    ),
                                ),
                              )
                            ],
                          ),
                        );
                      }
                    }),
              ),

恕我直言,您的第一个快照没有问题...这是 flutter 方式。但是如果您想使用 for loop 方式,那么您可以使用 SingleChildScrollView

Be careful because SingleChildScrollView will render all of your items at once which is very heavy

import 'package:flutter/material.dart';

class SamplePage extends StatefulWidget {

    SamplePage({Key key}) : super(key: key);

    @override
    State<StatefulWidget> createState() => SamplePageState();

}

class SamplePageState extends State<SamplePage> {

    List<Map<String, dynamic>> distributions = List();

    @override
    void initState() {
        super.initState();
        distributions.add(<String, String>{
            'cover_url': '', 'title': 'Blinding Lights',
        });
        distributions.add(<String, String>{
            'cover_url': '', 'title': 'Blinding Lights',
        });
        distributions.add(<String, String>{
            'cover_url': '', 'title': 'Blinding Lights',
        });
        distributions.add(<String, String>{
            'cover_url': '', 'title': 'Blinding Lights',
        });
        distributions.add(<String, String>{
            'cover_url': '', 'title': 'Blinding Lights',
        });
        distributions.add(<String, String>{
            'cover_url': '', 'title': 'Blinding Lights',
        });
    }

    @override
    Widget build(BuildContext context) {
        final children = <Widget>[];
        for (int i = 0; i < distributions?.length ?? 0; i++) {
            if (distributions[i] == null) {
                children.add(Center(child: CircularProgressIndicator()));
            }
            else {
                children.add(ItemView(distribution: distributions[i]));
            }
        }
        return Scaffold(
            body: Container(
                height: (MediaQuery.of(context)).size.height * 0.25,
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(children: children)
                ),
            ),
        );
    }

}

class ItemView extends StatelessWidget {

    final Map<String, dynamic> distribution;

    ItemView({Key key, this.distribution}) : super(key: key);

    @override
    Widget build(BuildContext context) {
        return Padding(
            padding: EdgeInsets.all(5.0),
            child: Column(children: <Widget>[
                Container(
                    width: (MediaQuery.of(context)).size.width * 0.3,
                    decoration: BoxDecoration(color: Colors.grey[850], borderRadius: BorderRadius.all(Radius.circular(5)),),
                    child: Center(
                        child: GestureDetector(
                            onTap: () => playMySong(distribution),
                            child: Image.network(distribution['cover_url'].toString(), fit: BoxFit.fitHeight),
                        )
                    ),
                ),
                Padding(
                    padding: const EdgeInsets.all(5.0),
                    child: Text(distribution['title'].toString(), style: TextStyle(color: Colors.white),),
                )
            ])
        );
    }

    void playMySong(Map<String, dynamic> distribution) {

    }

}