将数据发送到新的屏幕抖动

时间:2019-09-18 15:26:54

标签: android mobile flutter flutter-layout

我想将名称和ID保存到列表的不同元素中,以将数据发送到新屏幕。

怎么办?

我使用“共享的偏好设置”观看,但我们无法显示列表。 在我的代码中,我只需要保存切换为true的元素。

严重的是,这个屏幕今天让我不高兴

向我解释如何恢复结果,并可以发送下一页,下一个屏幕

我的主题模型:

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

class Theme {
  int id;
  String name;


  Theme({this.id, this.name});

  factory Theme.fromJson(Map<String, dynamic> json) {
    return Theme(
      id: json['id'],
      name: json['name'],
    );
  }

  Future<List<Theme>> getThemes() async {
    String url = 'http://10.0.2.2:3000/v1/api/theme';
    final response =
        await http.get(url, headers: {"Accept": "application/json"});

    if (response.statusCode == 200) {
      List themesList = jsonDecode(response.body);
      List<Theme> themes = [];
      for (var themeMap in themesList) {
        themes.add(Theme.fromJson(themeMap));

      }
      return themes;
    } else {
      throw Exception('Failed to load themes');
    }
  }
}

我的主题屏幕:

class _ThemePage extends State<ThemePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text("Blackbox"),
        leading: Image.asset(
          'assets/img/logo_ineat.png',
          fit: BoxFit.contain,
          height: 32,
        ),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Container(
                margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                child: new Text('Sélection du profil',
                    style: new TextStyle(
                        fontSize: 24, fontWeight: FontWeight.bold)),
                alignment: Alignment.topCenter),
            new Flexible(
              child: new Container(
                child: new FutureBuilder<List<t.Theme>>(
                    future: t.Theme().getThemes(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      if (snapshot.hasData) {
                        if (snapshot.data != null) {
                          return new Column(
                            children: <Widget>[
                              new Expanded(
                                child: new ListView.builder(
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, index) {
                                    return ThemeListViewItem(
                                        title: snapshot.data[index].name);
                                  },
                                ),
                              ),
                            ],
                          );
                        }
                      } else {
                        new Text("Loading...");
                        return new CircularProgressIndicator();
                      }
                    }),
              ),
            ),
            new Container(
              margin: EdgeInsets.only(right: 10.0),
              child: new RaisedButton.icon(
                onPressed: () {
                  /*Navigator.pushReplacement(context,
                      MaterialPageRoute(builder: (context) => Technologies()));*/
                },
                label: Text('Suivant'),
                icon: Icon(Icons.navigate_next),
              ),
              alignment: Alignment.bottomRight,
            ),
          ],
        ),
      ),
    );
  }
}

class ThemeListViewItem extends StatefulWidget {
  final String title;

  const ThemeListViewItem({Key key, this.title}) : super(key: key);

  @override
  _ThemeListViewItemState createState() => _ThemeListViewItemState();
}

class _ThemeListViewItemState extends State<ThemeListViewItem> {
  bool isSwitched = false;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: new Text(widget.title),
      trailing: new Switch(
        value: isSwitched,
        activeColor: Colors.pink,
        activeTrackColor: Colors.pinkAccent,
        onChanged: (value) {
          setState(() async {
            isSwitched = value;
          });
        },
      ),
    );
  }
}


编辑:

主题模型:

  Future<String> getThemeId() async {
prefs = await SharedPreferences.getInstance();
return prefs.getString(_kThemeId) ?? 'id';

}

将来的setThemeId(int id)异步{     prefs =等待SharedPreferences.getInstance();

return prefs.setInt(_kThemeId, id);

}

技术模型:

Future<List<Technology>> getTechnologies() async {

    String idTheme = theme.getThemeId().toString();
    String url = 'http://10.0.2.2:3000/v1/api/theme/${idTheme}/technology';
    final response =
        await http.get(url, headers: {"Accept": "application/json"});

    if (response.statusCode == 200) {
      List technosList = jsonDecode(response.body);
      List<Technology> technos = [];
      for (var technoMap in technosList) {
        technos.add(Technology.fromJson(technoMap));
      }
      return technos;
    } else {
      throw Exception('Failed to load technos');
    }
  }
}

1 个答案:

答案 0 :(得分:0)

https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments在这里您可以找到通过Navigator传递参数所需的一切。我相信,在您的情况下,您只需要在重定向时传递参数即可,而无需使用SharedPreferences。

链接中的第四点对您来说应该非常有用,但是我建议您阅读整个页面,因为它从一开始就描述了解决方案。