【发布时间】:2021-11-17 10:51:20
【问题描述】:
我正在做一个项目,我通过 React JS 完成了我的网站。 现在我正在使用颤振开发应用程序。所有后端都是使用 aws amplify 完成的。 在处理颤振时,我遇到了奇怪的问题。当我在颤动中查询 aws 表时,我得到的是空列表,因为该表上有数据,所以在 React 上查询同一个表可以工作并且工作到现在。
所以我计划创建一些测试文件来检查问题,所以我创建了测试颤振项目和测试反应项目。
我会在下面添加代码
。做了测试后才知道,我从flutter保存的数据只能用flutter查询,而react保存的数据只能通过react查询,因为是同一张表,同一个区域,都是一样的。为什么会出现这种奇怪的行为。
如您所见,查询同一张表但结果不同,并且颤振创建的数据未显示在 React 应用程序中,甚至在此处
flutter的代码如下: Main.dart:
import 'package:amplify_datastore/amplify_datastore.dart';
import 'package:amplify_flutter/amplify.dart';
import 'package:flutter/material.dart';
import 'package:my_app/amplifyconfiguration.dart';
import 'models/ModelProvider.dart';
import 'screens/homepage.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureAmplify();
runApp(MyApp());
}
Future<void> configureAmplify() async {
Amplify.addPlugin(AmplifyDataStore(modelProvider: ModelProvider.instance));
try {
await Amplify.configure(amplifyconfig);
} catch (e) {
print("Amplify is alreay configured");
}
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
主页:
import 'package:amplify_flutter/amplify.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_app/models/Person.dart';
class HomePage extends StatelessWidget {
Future<void> initTodos() async {
final model = Person(name: "runzun");
await Amplify.DataStore.save(model);
final persons = await Amplify.DataStore.query(Person.classType);
print(persons);
print('======================');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hello'),
),
body: Center(
child: GestureDetector(
onTap: () async {
await initTodos();
// var todos = Todo(name: "runzun", description: "this is a blog");
// await Amplify.DataStore.save(todos);
},
child: Text('Add todos')),
),
);
}
}
型号: ModelProvider.dart
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
// ignore_for_file: public_member_api_docs
import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart';
import 'Person.dart';
export 'Person.dart';
class ModelProvider implements ModelProviderInterface {
@override
String version = "115942e9588e46ca9df7bb771727f5c7";
@override
List<ModelSchema> modelSchemas = [Person.schema];
static final ModelProvider _instance = ModelProvider();
static ModelProvider get instance => _instance;
ModelType getModelTypeByModelName(String modelName) {
switch(modelName) {
case "Person": {
return Person.classType;
}
break;
default: {
throw Exception("Failed to find model in model provider for model name: " + modelName);
}
}
}
}
Person.dart:
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
// ignore_for_file: public_member_api_docs
import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart';
import 'package:flutter/foundation.dart';
/** This is an auto generated class representing the Person type in your schema. */
@immutable
class Person extends Model {
static const classType = const _PersonModelType();
final String id;
final String? _name;
final String? _des;
@override
getInstanceType() => classType;
@override
String getId() {
return id;
}
String get name {
try {
return _name!;
} catch(e) {
throw new DataStoreException(DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, recoverySuggestion: DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, underlyingException: e.toString());
}
}
String? get des {
return _des;
}
const Person._internal({required this.id, required name, des}): _name = name, _des = des;
factory Person({String? id, required String name, String? des}) {
return Person._internal(
id: id == null ? UUID.getUUID() : id,
name: name,
des: des);
}
bool equals(Object other) {
return this == other;
}
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Person &&
id == other.id &&
_name == other._name &&
_des == other._des;
}
@override
int get hashCode => toString().hashCode;
@override
String toString() {
var buffer = new StringBuffer();
buffer.write("Person {");
buffer.write("id=" + "$id" + ", ");
buffer.write("name=" + "$_name" + ", ");
buffer.write("des=" + "$_des");
buffer.write("}");
return buffer.toString();
}
Person copyWith({String? id, String? name, String? des}) {
return Person(
id: id ?? this.id,
name: name ?? this.name,
des: des ?? this.des);
}
Person.fromJson(Map<String, dynamic> json)
: id = json['id'],
_name = json['name'],
_des = json['des'];
Map<String, dynamic> toJson() => {
'id': id, 'name': _name, 'des': _des
};
static final QueryField ID = QueryField(fieldName: "person.id");
static final QueryField NAME = QueryField(fieldName: "name");
static final QueryField DES = QueryField(fieldName: "des");
static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) {
modelSchemaDefinition.name = "Person";
modelSchemaDefinition.pluralName = "People";
modelSchemaDefinition.addField(ModelFieldDefinition.id());
modelSchemaDefinition.addField(ModelFieldDefinition.field(
key: Person.NAME,
isRequired: true,
ofType: ModelFieldType(ModelFieldTypeEnum.string)
));
modelSchemaDefinition.addField(ModelFieldDefinition.field(
key: Person.DES,
isRequired: false,
ofType: ModelFieldType(ModelFieldTypeEnum.string)
));
});
}
class _PersonModelType extends ModelType<Person> {
const _PersonModelType();
@override
Person fromJson(Map<String, dynamic> jsonData) {
return Person.fromJson(jsonData);
}
}
后端架构.graphql:
type Person @model {
id: ID!
name: String!
des: String
}
React JS 应用程序: index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Amplify from 'aws-amplify';
import aws_exports from './../src/aws-exports';
Amplify.configure(aws_exports);
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
app.js:
import logo from './logo.svg';
import './App.css';
import { useEffect } from 'react';
import { API, graphqlOperation } from 'aws-amplify';
import { listPeople } from './graphql/queries';
import { createPerson } from './graphql/mutations';
function App() {
useEffect(() => {
const test = async () => {
try {
await API.graphql(
graphqlOperation(createPerson, {
input: {
name: 'runzun Node',
},
})
);
const result = await API.graphql(graphqlOperation(listPeople));
console.log(result);
} catch (err) {
console.log(err);
}
// const peopleList = result.data.listPeople;
};
test();
}, []);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
graphql 查询:
/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const getPerson = /* GraphQL */ `
query GetPerson($id: ID!) {
getPerson(id: $id) {
id
name
des
createdAt
updatedAt
}
}
`;
export const listPeople = /* GraphQL */ `
query ListPeople(
$filter: ModelPersonFilterInput
$limit: Int
$nextToken: String
) {
listPeople(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
name
des
createdAt
updatedAt
}
nextToken
}
}
`;
graphql 突变:
/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const createPerson = /* GraphQL */ `
mutation CreatePerson(
$input: CreatePersonInput!
$condition: ModelPersonConditionInput
) {
createPerson(input: $input, condition: $condition) {
id
name
des
createdAt
updatedAt
}
}
`;
export const updatePerson = /* GraphQL */ `
mutation UpdatePerson(
$input: UpdatePersonInput!
$condition: ModelPersonConditionInput
) {
updatePerson(input: $input, condition: $condition) {
id
name
des
createdAt
updatedAt
}
}
`;
export const deletePerson = /* GraphQL */ `
mutation DeletePerson(
$input: DeletePersonInput!
$condition: ModelPersonConditionInput
) {
deletePerson(input: $input, condition: $condition) {
id
name
des
createdAt
updatedAt
}
}
`;
后端架构.graphql
type Person @model {
id: ID!
name: String!
des: String
}
【问题讨论】:
标签: reactjs flutter graphql aws-amplify