颤振循环

时间:2020-01-29 01:37:28

标签: android ios flutter appcelerator

您好,我正在学习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,
                                    ),
                                ),
                              )
                            ],
                          ),
                        );
                      }
                    }),
              ),

1 个答案:

答案 0 :(得分:1)

Imho,您的第一个快照没有错...这是扑朔迷离的方式。但是,如果您想使用for loop的方式,则可以使用SingleChildScrollView

请注意,因为SingleChildScrollView会一次渲染您所有的项目,这很繁琐

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) {

    }

}