build method
Describes the part of the user interface represented by this widget.
The framework calls this method in a number of different situations. For example:
- After calling initState.
- After calling didUpdateWidget.
- After receiving a call to setState.
- After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).
- After calling deactivate and then reinserting the State object into the tree at another location.
This method can potentially be called in every frame and should not have any side effects beyond building a widget.
The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.
Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor, the given BuildContext, and the internal state of this State object.
The given BuildContext contains information about the location in the
tree at which this widget is being built. For example, the context
provides the set of inherited widgets for this location in the tree. The
BuildContext argument is always the same as the context
property of
this State object and will remain the same for the lifetime of this
object. The BuildContext argument is provided redundantly here so that
this method matches the signature for a WidgetBuilder.
Design discussion
Why is the build method on State, and not StatefulWidget?
Putting a Widget build(BuildContext context)
method on State rather
than putting a Widget build(BuildContext context, State state)
method
on StatefulWidget gives developers more flexibility when subclassing
StatefulWidget.
For example, AnimatedWidget is a subclass of StatefulWidget that
introduces an abstract Widget build(BuildContext context)
method for its
subclasses to implement. If StatefulWidget already had a build method
that took a State argument, AnimatedWidget would be forced to provide
its State object to subclasses even though its State object is an
internal implementation detail of AnimatedWidget.
Conceptually, StatelessWidget could also be implemented as a subclass of StatefulWidget in a similar manner. If the build method were on StatefulWidget rather than State, that would not be possible anymore.
Putting the build function on State rather than StatefulWidget also
helps avoid a category of bugs related to closures implicitly capturing
this
. If you defined a closure in a build function on a
StatefulWidget, that closure would implicitly capture this
, which is
the current widget instance, and would have the (immutable) fields of that
instance in scope:
// (this is not valid Flutter code)
class MyButton extends StatefulWidgetX {
MyButton({super.key, required this.color});
final Color color;
@override
Widget build(BuildContext context, State state) {
return SpecialWidget(
handler: () { print('color: $color'); },
);
}
}
For example, suppose the parent builds MyButton
with color
being blue,
the $color
in the print function refers to blue, as expected. Now,
suppose the parent rebuilds MyButton
with green. The closure created by
the first build still implicitly refers to the original widget and the
$color
still prints blue even through the widget has been updated to
green; should that closure outlive its widget, it would print outdated
information.
In contrast, with the build function on the State object, closures created during build implicitly capture the State instance instead of the widget instance:
class MyButton extends StatefulWidget {
const MyButton({super.key, this.color = Colors.teal});
final Color color;
// ...
}
class MyButtonState extends State<MyButton> {
// ...
@override
Widget build(BuildContext context) {
return SpecialWidget(
handler: () { print('color: ${widget.color}'); },
);
}
}
Now when the parent rebuilds MyButton
with green, the closure created by
the first build still refers to State object, which is preserved across
rebuilds, but the framework has updated that State object's widget
property to refer to the new MyButton
instance and ${widget.color}
prints green, as expected.
See also:
- StatefulWidget, which contains the discussion on performance considerations.
Implementation
@override
Widget build(BuildContext context) {
final chatProvider = Provider.of<ChatProvider>(context);
final _agentDetails = chatProvider.agentDetails;
final _isDeployed = chatProvider.isDeployed ?? false; // Default to false if null
Size screenSize = MediaQuery.of(context).size;
double containerHeight = screenSize.height * 0.1;
if (_agentDetails == null) {
// Handle the case where _agentDetails is null
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: SpinKitCubeGrid(
color: ColorTheme.primary,
),
),
);
}
_agentName = _agentDetails.displayName;
return Scaffold(
// backgroundColor: ColorTheme.primary.withOpacity(0.05),
backgroundColor: Colors.white,
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
textDirection: TextDirection.ltr,
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
_agentDetails.displayName!,
style: GoogleFonts.questrial(
color: ColorTheme.secondary,
fontSize: 20,
),
),
),
Align(
alignment: Alignment.centerLeft,
child: Text(
_isOnline ? "online" : "offline",
style: GoogleFonts.montserrat(
color: ColorTheme.secondary,
fontSize: 10,
),
),
),
],
),
centerTitle: false,
titleTextStyle: GoogleFonts.questrial(
color: ColorTheme.secondary,
fontSize: 20
),
backgroundColor: ColorTheme.primary,
leading: Container(
margin: EdgeInsets.all(10),
child:Stack(
children: [
Container(
width: 50, // Ensure container width matches image size
height: 50, // Ensure container height matches image size
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorTheme.secondary, // Border color
width: 1, // Border width
),
),
child: GestureDetector(
onTap: () {
if(_agentDetails.description != null) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
backgroundColor: ColorTheme.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
titlePadding: EdgeInsets.all(16.0),
contentPadding: EdgeInsets.all(16.0),
title: Text(
'Description',
style: GoogleFonts.questrial(
color: ColorTheme.secondary,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
content: SingleChildScrollView(
child: Text(
_agentDetails.description! ,style: GoogleFonts.questrial(
color: ColorTheme.secondary,
fontSize: 16,
fontWeight: FontWeight.normal,
),
),
),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: ColorTheme.primary, backgroundColor: ColorTheme.secondary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0),
),
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Got It',
style: GoogleFonts.questrial(
color: ColorTheme.primary,
fontWeight: FontWeight.bold,
),
),
),
],
);
},
);
}
},
child: ClipOval(
child: _agentDetails == null || _agentDetails.image == null
? Image.asset(
"assets/haiva.png",
height: 30,
width: 30,
fit: BoxFit.cover,
)
: Image.network(
_agentDetails.image!,
height: 30,
width: 30,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Image.asset(
"assets/haiva.png",
height: 30,
width: 30,
fit: BoxFit.cover,
);
},
),
),
),
),
if (_isOnline)
Positioned(
bottom: 1,
right: 0,
child: Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: _isOnline ? Colors.green : Colors.red, // Green for online, Red for offline
shape: BoxShape.circle,
border: Border.all(
color: Colors.white,
width: 1,
),
),
),
),
Positioned(
bottom: 1,
right: 0,
child: Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: _isOnline ?null: Colors.red, // Green for online, Red for offline
shape: BoxShape.circle,
border: Border.all(
color: Colors.white,
width: 1,
),
),
),
),
],
),
),
actions: [
IconButton(
icon: Icon(
isSpeaking ? Icons.volume_up_rounded : Icons.volume_off,
color: ColorTheme.secondary,
),
onPressed: () {
setState(() {
if (isSpeaking) {
stopSpeaking; // Call method to stop speaking
} else {
// Start speaking
}
isSpeaking = !isSpeaking; // Toggle the speaking state
});
},
),
PopupMenuButton<String>(
popUpAnimationStyle: AnimationStyle.noAnimation,
tooltip: 'Show languages',
shadowColor: ColorTheme.primary.withOpacity(1),
color: ColorTheme.primary,
icon: Icon(Icons.translate, color: ColorTheme.secondary),
onSelected: (String value) {
setState(() {
_currentLocaleId = value;
});
// print("Selected locale: $_currentLocaleId");
// _speechToText.stop();
// _speechToText.listen(localeId: _currentLocaleId);
},
itemBuilder: (BuildContext context) {
// Assuming _agentDetails.languages is a list of locale identifiers
final List<String> localeIdentifiers = _agentDetails.languages ?? ["en-US", "ta-IN"];
return _buildLanguageMenuItems(localeIdentifiers);
},
)
,IconButton(
onPressed: () {
_refreshChat();
// _changeTheme();
},
icon: Icon(
CupertinoIcons.refresh,
color: ColorTheme.secondary,
),
),
if (widget.agentSetting)
IconButton(
icon: Icon(
Icons.settings,
color: ColorTheme.secondary,
), // Customize your icon here
onPressed: () {
showCupertinoDialog(
context: context,
builder: (BuildContext context) {
return CupertinoAlertDialog(
title: Text("Redirect to Agent Settings"),
content: Text("This action will leave the chat session, are you sure you want to proceed?"),
actions: <Widget>[
CupertinoDialogAction(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context).pop();
},
),
CupertinoDialogAction(
child: Text("OK"),
onPressed: () {
// Add action here
Navigator.of(context).pop();
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => SettingsPage(agentId: widget.agentId, isAction: widget.isAction, agentSetting: widget.agentSetting, menuItems: widget.menuItems),
),
);
},
),
],
);
},
);
},
),
if(widget.isAction)
IconButton( onPressed: () => _showActionSheet(context), icon: Icon(Icons.menu), color: ColorTheme.secondary,),
],
),
body: Stack(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(1, 16, 1, 16),
child: Column(
children: <Widget>[
SizedBox(height: 10),
Expanded(
child: ListView.builder(
controller: _scrollController,
itemCount: _messages.length,
itemBuilder: (context, index) {
if (welcomemessagedata.type =="screen" && index == 0 && _messages[index].type == MessageType.bot) {
return SizedBox.shrink();
}
final message = _messages[index];
return Column(
children: [
ChatBubbleHaiva(
message: message,
onSendMessage: (text, isClicked,) => sendMessage(text, action: isClicked),
onFormSubmit: (formData) {// Debugging line
sendMessage('the form data is', displayMessage: false, action: _isclicked, payload: formData);
},
agentDetails: _agentDetails,
locale: _currentLocaleId,
stopSpeaking: !isSpeaking,
)
,SizedBox(height: 10),
],
);
},
),
),
Visibility(
visible: _isWelcomeVisible && welcomemessagedata.type == "screen",
child: Column(
children: [
ClipOval(
child: _agentDetails == null || _agentDetails.image == null
? Image.asset("assets/haiva.png", height: 50, width: 50)
: Image.network(
_agentDetails.image!,
height: 50,
width: 50,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Image.asset("assets/haiva.png", height: 50, width: 50);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
_agentDetails.description ?? "Ask any questions you have, and I'll provide all the information you need!",
style: GoogleFonts.questrial(
color: ColorTheme.accent.withOpacity(1),
fontSize: 16,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
softWrap: true,
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: GridView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // Number of columns
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: 1, // Adjust to fit your needs
),
itemCount: welcomemessagedata.data['sampleQuestions']?.length ?? 0,
itemBuilder: (context, index) {
// Ensure sampleQuestions is correctly accessed
List<String> sampleQuestions = List<String>.from(welcomemessagedata.data['sampleQuestions'] ?? []);
return GestureDetector(
onTap: () {
sendMessage(sampleQuestions[index]);
setState(() {
_isWelcomeVisible = false; // Hide the welcome message when a question is clicked
});
},
child: Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: ColorTheme.primary.withOpacity(0.2),
borderRadius: BorderRadius.circular(8.0),
border: Border.all(
color: ColorTheme.primary,
width: 1.0,
),
),
child: Center(
child: Text(
sampleQuestions[index],
style: GoogleFonts.questrial(
fontSize: 12,
),
textAlign: TextAlign.center,
),
),
),
);
},
),
),
],
),
),
Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: Container(
decoration: BoxDecoration(
color: ColorTheme.primary.withOpacity(0.2),
borderRadius: BorderRadius.circular(12.0),
border: Border.all(
color: ColorTheme.primary,
width: 1,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(6.0),
// child: IconButton(
// icon: Icon(Icons.attach_file),
// color: ColorTheme.accent,
// iconSize: 16,
// onPressed: _uploadFile,
// ),
),
Expanded(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 100, // Adjust this value as needed
),
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(2.0),
child: TextField(
enabled: _isDeployed,
textInputAction: TextInputAction.send,
cursorColor: ColorTheme.accent,
maxLines: null,
keyboardType: TextInputType.multiline,
controller: _controller,
decoration: InputDecoration(
hintText: _isDeployed?'Enter a message ...':'Agent is not deployed. Please deploy to enter message ...',
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(vertical: 16.0),
),
style: GoogleFonts.questrial(
color: ColorTheme.accent,
fontSize: 14,
fontWeight: FontWeight.bold,
),
onSubmitted: (text) => _isloading ? null : sendMessage(text),
),
),
),
),
),
if (_speechEnabled && _agentDetails.isSpeech2text == true)
Padding(
padding: const EdgeInsets.fromLTRB(0,6,6,6),
child: Container(
decoration: BoxDecoration(
color: ColorTheme.primary,
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: IconButton(
icon: Icon(
_speechListening ? CupertinoIcons.mic_fill : CupertinoIcons.mic_slash,
color: ColorTheme.secondary,
size: 18,
),
onPressed: () {
if (_speechListening) {
// _controller.clear();
_stopListening();
} else {
// _controller.clear();
_startListening();
}
},
),
)
,
),
Padding(
padding: const EdgeInsets.fromLTRB(0,6,6,6),
child: Container(
decoration: BoxDecoration(
color: ColorTheme.primary,
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: IconButton(
color: ColorTheme.secondary,
icon: Icon(_isloading ? Icons.stop_circle : Icons.send_rounded),
iconSize: 16,
onPressed: () {
// if(_prevMessage != null ){
// sendMessage(_controller.text);
// sendMessage(_controller.text);
// }
_isloading ? null : sendMessage(_controller.text);
setState(() {
_controller.clear();
});
},
),
),
),
],
),
),
),
],
),
),
],
),
),
if (_messages.isNotEmpty && _messages.last.text != null && _messages.last.text!.contains('Order') && _messages.last.text!.contains('successful'))
ConfettiWidget(
confettiController: _confettiController,
blastDirectionality: BlastDirectionality.explosive,
numberOfParticles: 30,
shouldLoop: false,
createParticlePath: (size) {
return createStarPath(8.0, 4.0, 10); // Adjust radius and number of points as needed
},
colors: [Colors.green, Colors.blue, Colors.pink, Colors.orange],
),
],
),
);
}