给出一个类,如何从字段字典中创建它的实例?这是一个示例来说明我的问题:
from typing import Tuple, Mapping, Any
def new_instance(of: type, with_fields: Mapping[str, Any]):
"""How to implement this?"""
return ...
class A:
"""Example class"""
def __init__(self, pair: Tuple[int, int]):
self.first = pair[0]
self.second = pair[1]
def sum(self):
return self.first + self.second
# Example use of new_instance
a_instance = new_instance(
of=A,
with_fields={'first': 1, 'second': 2}
)
答案 0 :(得分:1)
请参见How to create a class instance without calling initializer?绕过初始化程序。然后从字典中设置属性。
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'home_page.dart';
import 'auth.dart';
import 'login_page.dart';
void main() => runApp(
ChangeNotifierProvider<AuthService>(
child: MyApp(),
builder: (BuildContext context) {
return AuthService();
},
),
);
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: FutureBuilder<FirebaseUser>(
future: Provider.of<AuthService>(context).getUser(),
builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// log error to console
if (snapshot.error != null) {
print("error");
return Text(snapshot.error.toString());
}
// redirect to the proper page
return snapshot.hasData ? HomePage(snapshot.data) : LoginPage();
} else {
// show loading indicator
return LoadingCircle();
}
},
),
);
}
}
class LoadingCircle extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
child: CircularProgressIndicator(),
alignment: Alignment(0.0, 0.0),
),
);
}