将 Rails API 连接到 Flutter UI 非常简单,有几个关于状态管理的注意事项,但 Google 建议使用 BLoC 模式,它与 Rails 配合得非常好。
现在我不打算详细介绍实现 BLoC 模式的细节,但我会在底部留下一些围绕这个主题的链接。
第一步是检查颤振文档,他们有一些不错的食谱,我将在下面使用 Rails 生成器进行调整。 https://flutter.dev/docs/cookbook/networking/fetch-data
- 创建帖子资源:
rails g resource post title:string body:string
- 运行
rails db:migrate。
- 使用 Rails 控制台创建帖子
- 在您的颤振应用程序 (main.dart) 中,我假设它是一个全新的应用程序:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final response =
await http.get('http://10.0.2.2:3000/posts/1');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int id;
final String title;
final String body;
Post({this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
- 启动在 3000 端口上运行的 rails 服务器
- 启动颤振应用
真的是这样。 Rails 和 Flutter 完美结合,Flutter Web 即将问世……在某个时候……我真的很兴奋。
其他一些资源:
Flutter 和 Rails CLI(仍然是一个 WIP,但可以实现)https://rubygems.org/gems/frap
状态管理:
https://www.didierboelens.com/2018/08/reactive-programming---streams---bloc/
https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1
一堆例子
https://github.com/flutter/samples/blob/master/INDEX.md