将Strapi Datas扑来

发布于 2025-01-31 18:10:20 字数 2794 浏览 3 评论 0 原文

*读了许多文档后,我看到扑飞与strapi v4不兼容,要将其与颤动一起使用,您必须使用一个 v4下的Strapi项目。

正在尝试将我的Flutter应用程序连接到Strapi。

我跟随官方的Strapi Tuto进行扑打,并在YouTube上进行了一些视频,但我坚持阅读Datas。

当我的观点开始时,我有一个错误:

_ typeerror(类型'_internallinkedhashmap< string,dynamic>'不是类型'iToble'的子类型)

我的完整代码。

import 'dart:convert';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:strapitests/user.dart';

class MyList extends StatefulWidget {
  const MyList({Key? key}) : super(key: key);

  @override
  State<MyList> createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  List<User> users = [];

  Future getAll() async {
    var data = await http.get(Uri.parse("http://10.0.2.2:1337/api/apis"));
    var jsonData = json.decode(data.body);

    for (var u in jsonData) {
      users.add(
        u['name'],
      );
    }
    return users;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: getAll(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == null) {
            return Container(
              child: const Center(
                child: Text("Loading..."),
              ),
            );
          } else {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(snapshot.data[index].name),
                  subtitle: Text(snapshot.data[index].email),
                );
              },
            );
          }
        },
      ),
    );
  }
}

这是 “用户”课:

class User {
  String name;
  String email;
  String password;
  User(this.name, this.email, this.password);
}

当我在浏览器上进行“获取”时,结果是:

"data": [
{
"id": 1,
"attributes": {
"name": "john",
"password": "dfdf",
"email": "[email protected]",
"createdAt": "2022-05-23T20:38:27.725Z",
"updatedAt": "2022-05-23T20:38:28.466Z",
"publishedAt": "2022-05-23T20:38:28.464Z"
}
},
{
"id": 2,
"attributes": {
"name": "text",
"password": "mp",
"email": "mail",
"createdAt": "2022-05-23T20:47:56.717Z",
"updatedAt": "2022-05-23T20:47:56.717Z",
"publishedAt": "2022-05-23T20:47:56.712Z"
}
},
{
"id": 3,
"attributes": {
"name": "name",
"password": "mp",
"email": "mail",
"createdAt": "2022-05-23T20:52:07.911Z",
"updatedAt": "2022-05-23T20:52:07.911Z",
"publishedAt": "2022-05-23T20:52:07.910Z"
}
}
],

感谢您的帮助!

*After many documentations readed, I saw that Flutter is not compatible with strapi v4, to use it with Flutter, you have to use a
strapi project under v4.

I'm trying to connect my Flutter app to Strapi.

I followed the official Strapi tuto for flutter and some videos on Youtube about it but I'm stuck to read datas.

I have this error while my view begins:

_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable')

This is my full code for this view:

import 'dart:convert';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:strapitests/user.dart';

class MyList extends StatefulWidget {
  const MyList({Key? key}) : super(key: key);

  @override
  State<MyList> createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  List<User> users = [];

  Future getAll() async {
    var data = await http.get(Uri.parse("http://10.0.2.2:1337/api/apis"));
    var jsonData = json.decode(data.body);

    for (var u in jsonData) {
      users.add(
        u['name'],
      );
    }
    return users;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: getAll(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == null) {
            return Container(
              child: const Center(
                child: Text("Loading..."),
              ),
            );
          } else {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(snapshot.data[index].name),
                  subtitle: Text(snapshot.data[index].email),
                );
              },
            );
          }
        },
      ),
    );
  }
}

And this is my 'User' class:

class User {
  String name;
  String email;
  String password;
  User(this.name, this.email, this.password);
}

While i make a 'GET' on my browser, the result is:

"data": [
{
"id": 1,
"attributes": {
"name": "john",
"password": "dfdf",
"email": "[email protected]",
"createdAt": "2022-05-23T20:38:27.725Z",
"updatedAt": "2022-05-23T20:38:28.466Z",
"publishedAt": "2022-05-23T20:38:28.464Z"
}
},
{
"id": 2,
"attributes": {
"name": "text",
"password": "mp",
"email": "mail",
"createdAt": "2022-05-23T20:47:56.717Z",
"updatedAt": "2022-05-23T20:47:56.717Z",
"publishedAt": "2022-05-23T20:47:56.712Z"
}
},
{
"id": 3,
"attributes": {
"name": "name",
"password": "mp",
"email": "mail",
"createdAt": "2022-05-23T20:52:07.911Z",
"updatedAt": "2022-05-23T20:52:07.911Z",
"publishedAt": "2022-05-23T20:52:07.910Z"
}
}
],

Thanks for helping!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不打扰别人 2025-02-07 18:10:20

首先,您需要从JSON解码您的用户。由于这是一个简单的类,因此您只需为 user class fromjson 构造函数编写快速类:

class User {
  String name;
  String email;
  String password;
  User(this.name, this.email, this.password);

  factory User.fromJson(Map<String, dynamic> json) {
    final attributes = json['attributes'];
    return User(
      attributes['name'],
      attributes['email'],
      attributes['password'],
    );
  }
}

接下来,您收到的数据是映射,无法迭代通过前循环。

取而代之的是,迭代以为单位的列表“数据” ,并用 user.fromjson 构造函数对每个元素进行解码:

Future<List<User>> getAll() async {
  var data = await http.get(Uri.parse("http://10.0.2.2:1337/api/apis"));
  var jsonData = json.decode(data.body);

  final users = jsonData['data'];

  return users.map((userJson) => User.fromJson(userJson)).toList();
}

最后,因为您使用的是 FutureBuilder ,您实际上不需要它是一个状态的小部件,也不需要将用户作为类属性存储。您可以简单地使用快照中返回的列表 - 尽管您需要更改代码,以使未来是最终成员,以便小部件不会在每个构建上构造新的未来:

class MyList extends StatelessWidget {
  late final Future<List<User>> users = getAll();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: users,
        // ...
      ),
    );
  }
}

此外 -就您的问题而言,但是最好研究避免在服务器上存储密码的方法。如果您确实存储密码,请绝对避免在生产应用程序的任何API响应中返回它们:)。

以下是有关该主题的几篇好文章:

https:https:https:https:https: //auth0.com/blog/hashing-passwords-one-way-way-to-to-security/

https://auth0.com/blog/adding-salt-salt-salt-to-hashing-a-better-a-better-way-way-way-way-to-store-passwords/ < /a>

First, you will need to decode your users from JSON. Since this is a simple class, you can just write a quick fromJson constructor for your User class:

class User {
  String name;
  String email;
  String password;
  User(this.name, this.email, this.password);

  factory User.fromJson(Map<String, dynamic> json) {
    final attributes = json['attributes'];
    return User(
      attributes['name'],
      attributes['email'],
      attributes['password'],
    );
  }
}

Next, the data you're receiving is a map, which cannot be iterated through with a for-loop.

Instead, iterate over the list keyed by "data", and decode each element with the User.fromJson constructor we just defined:

Future<List<User>> getAll() async {
  var data = await http.get(Uri.parse("http://10.0.2.2:1337/api/apis"));
  var jsonData = json.decode(data.body);

  final users = jsonData['data'];

  return users.map((userJson) => User.fromJson(userJson)).toList();
}

Finally, since you're using a FutureBuilder, you actually don't need this to be a stateful widget, and you don't need to store users as a property on your class. You can simply use the list returned in the snapshot - Though you'll need change your code so that the Future is a final member so that the widget doesn't construct a new future on each build:

class MyList extends StatelessWidget {
  late final Future<List<User>> users = getAll();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: users,
        // ...
      ),
    );
  }
}

Also — and this is beside the point in terms of your question — but it's a good idea to look into ways of avoiding storing passwords on your server. If you do store passwords, definitely avoid returning them in any API responses for a production app :).

Here are a couple of good articles on the topic:

https://auth0.com/blog/hashing-passwords-one-way-road-to-security/

https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-store-passwords/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文