Вы можете скопировать и запустить полный код ниже
Вы можете использовать json["price"] == null
для проверки
фрагмент кода
factory Article.fromJson(Map<String, dynamic> json) => Article(
price: json["price"] == null ? null : Decimal.parse(json["price"]),
minPrice:
json["minPrice"] == null ? null : Decimal.parse(json["minPrice"]),
);
String jsonString1 = '''
{
"price":"12.3",
"minPrice" : "30.1"
}
''';
String jsonString2 = '''
{
"price":"12.9"
}
''';
выход
I/flutter (16685): price 12.3 minPrice 30.1
I/flutter (16685): price 12.9 minPrice null
полный код
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:decimal/decimal.dart';
Article articleFromJson(String str) => Article.fromJson(json.decode(str));
class Article {
Decimal price;
Decimal minPrice;
Article({
this.price,
this.minPrice,
});
factory Article.fromJson(Map<String, dynamic> json) => Article(
price: json["price"] == null ? null : Decimal.parse(json["price"]),
minPrice:
json["minPrice"] == null ? null : Decimal.parse(json["minPrice"]),
);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
String jsonString1 = '''
{
"price":"12.3",
"minPrice" : "30.1"
}
''';
Article article1 = articleFromJson(jsonString1);
print('price ${article1.price} minPrice ${article1.minPrice}');
String jsonString2 = '''
{
"price":"12.9"
}
''';
Article article2 = articleFromJson(jsonString2);
print('price ${article2.price} minPrice ${article2.minPrice}');
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}