The following error was thrown while building Builder method of my state class in my project:
════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building Builder:
type 'Null' is not a subtype of type 'String' in type cast
The relevant error-causing widget was
MaterialApp
lib\main.dart:32
When the exception was thrown, this was the stack
#0 _AddNewStoryScreenState.didChangeDependencies `package:database/screen/add_new_story_screen.dart:63`
The Widget:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../provider/item.dart';
import 'package:provider/provider.dart';
import '../provider/items.dart';
class AddNewStoryScreen extends StatefulWidget {
static const routeName = '/AddNewStory';
const AddNewStoryScreen({Key? key}) : super(key: key);
@override
State<AddNewStoryScreen> createState() => _AddNewStoryScreenState();
}
class _AddNewStoryScreenState extends State<AddNewStoryScreen> {
final _authorFocusNode = FocusNode();
final _contentFocusNode = FocusNode();
final _form = GlobalKey<FormState>();
late int selectedRadio;
setSelectedRadio(int val) {
setState(() {
selectedRadio = val;
});
}
var _isLoading = false;
var _editedItem = Item(
author: '',
category: '',
content: '',
id: DateTime.now().toString(),
startColor: '',
endColor: '',
title: '',
);
var _initValues = {
'title': '',
'content': '',
'category': '',
'author': '',
};
var _isInit = true;
@override
void initState() {
selectedRadio = 0;
super.initState();
}
@override
void didChangeDependencies() {
if (_isInit) {
final itemId = ModalRoute.of(context)?.settings.arguments as String;
// ignore: unnecessary_null_comparison
if (itemId != null) {
_editedItem =
Provider.of<Items>(context, listen: false).findById(itemId);
_initValues = {
'title': _editedItem.title.toString(),
'content': _editedItem.content.toString(),
'category': _editedItem.category.toString(),
'author': _editedItem.author.toString(),
};
}
}
_isInit = false;
super.didChangeDependencies();
}
@override
void dispose() {
_authorFocusNode.dispose();
_contentFocusNode.dispose();
super.dispose();
}
Future<void> _addItem(Item item) {
const url = 'https://*******.firebaseio.com/items.json';
return http
.post(
Uri.parse(url),
body: json.encode({
'title': item.title,
'author': item.author,
'content': item.content,
'id': DateTime.now().toString(),
'startColor': item.startColor,
'endColor': item.endColor,
'category': item.category,
}),
)
.then((response) {
_editedItem = Item(
title: _editedItem.title,
author: _editedItem.author,
category: _editedItem.category,
content: _editedItem.content,
id: json.decode(response.body)['name'],
startColor: _editedItem.startColor,
endColor: _editedItem.endColor,
);
});
}
Future<void> _saveForm() async {
final isValid = _form.currentState?.validate();
if (isValid == null) {
return;
}
if (_editedItem.id != null) {
await Provider.of<Items>(context, listen: false)
.updateItem(_editedItem.id.toString(), _editedItem);
} else {
try {
_addItem(_editedItem).then((_) {
setState(() {
_isLoading = false;
});
});
_form.currentState?.save();
setState(() {
_isLoading = true;
});
await Provider.of<Items>(context, listen: false)
.addProduct(_editedItem);
} catch (error) {
await showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('An error occured!'),
content: const Text('Something went wrong.'),
actions: [
FlatButton(
child: const Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add New Story'),
actions: [
IconButton(
icon: const Icon(Icons.save),
onPressed: _saveForm,
),
],
),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: Padding(
padding: const EdgeInsets.all(16.0),
child: Directionality(
textDirection: TextDirection.rtl,
child: Form(
key: _form,
child: ListView(
children: [
TextFormField(
initialValue: _initValues['title'],
decoration: const InputDecoration(
labelText: 'عنوان داستان',
),
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'عنوان داستان را وارد کنید';
}
return null;
},
onFieldSubmitted: (_) {
FocusScope.of(context)
.requestFocus(_authorFocusNode);
},
onSaved: (value) {
_editedItem = Item(
title: value,
author: _editedItem.author,
category: _editedItem.category,
content: _editedItem.content,
id: _editedItem.id,
startColor: _editedItem.startColor,
endColor: _editedItem.endColor,
);
},
),
TextFormField(
initialValue: _initValues['author'],
decoration: const InputDecoration(
labelText: 'اسم نویسنده',
),
focusNode: _authorFocusNode,
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'اسم نویسنده را وارد کنید';
}
return null;
},
onFieldSubmitted: (_) {
FocusScope.of(context)
.requestFocus(_contentFocusNode);
},
onSaved: (value) {
_editedItem = Item(
title: _editedItem.title,
author: value,
category: _editedItem.category,
content: _editedItem.content,
id: _editedItem.id,
startColor: _editedItem.startColor,
endColor: _editedItem.endColor,
);
},
),
TextFormField(
initialValue: _initValues['content'],
decoration: const InputDecoration(
labelText: 'متن داستان',
),
maxLines: 3,
keyboardType: TextInputType.multiline,
focusNode: _contentFocusNode,
validator: (value) {
if (value!.isEmpty) {
return 'متن داستان را وارد کنید';
}
return null;
},
onSaved: (value) {
_editedItem = Item(
title: _editedItem.title,
author: _editedItem.author,
category: _editedItem.category,
content: value,
id: _editedItem.id,
startColor: _editedItem.startColor,
endColor: _editedItem.endColor,
);
},
),
Column(
children: [
Card(
child: RadioListTile(
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val as int);
_editedItem = Item(
title: _editedItem.title,
author: _editedItem.author,
category: 'story',
content: _editedItem.content,
id: _editedItem.id,
startColor: Color(0xffFF5B95).toString(),
endColor: Color(0xffF8556D).toString(),
);
},
value: 1,
title: const Text('تخیلی'),
),
),
Card(
child: RadioListTile(
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val as int);
_editedItem = Item(
title: _editedItem.title,
author: _editedItem.author,
category: 'narrative',
content: _editedItem.content,
id: _editedItem.id,
startColor: Color(0xff6DC8F3).toString(),
endColor: Color(0xff73A1F9).toString(),
);
},
value: 2,
title: const Text('حکایت'),
),
),
Card(
child: RadioListTile(
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val as int);
_editedItem = Item(
title: _editedItem.title,
author: _editedItem.author,
category: 'qurani',
content: _editedItem.content,
id: _editedItem.id,
startColor: Color(0xffD76EF5).toString(),
endColor: Color(0xff8F7AFE).toString(),
);
},
value: 3,
title: const Text('قرآنی'),
),
),
Card(
child: RadioListTile(
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val as int);
_editedItem = Item(
title: _editedItem.title,
author: _editedItem.author,
category: 'success',
content: _editedItem.content,
id: _editedItem.id,
startColor: Color(0xffFFB157).toString(),
endColor: Color(0xffFFA057).toString(),
);
},
value: 4,
title: const Text('از تاریخ'),
),
),
],
),
],
),
),
),
),
);
}
}
@override
Widget build(BuildContext context) {
// TODO: implement build
throw UnimplementedError();
}
}
Also, when I hover over the build(BuildContext context) method, I see this warining:
The declaration 'build' isn't referenced.
Try removing the declaration of 'build'.dartunused_element
>Solution :
Either remove the ‘build’ method or change UnimplementedError() to other code.
@override
Widget build(BuildContext context) {
// TODO: implement build
throw UnimplementedError();
}
and change
ModalRoute.of(context)?.settings.arguments as String
to
ModalRoute.of(context)?.settings.arguments as String?