I’m creating a mobile app by using flutter framework. I want to add a search bar to my home page. Home page and Search bar files are separate than each other. Here is my home_screen.dart file
import 'package:amazon/widget/search_bar_widget.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: SearchBarWidget(),
body: Center(
child: Text("Home Screen"),
),
);
}
}
And here is my search_bar_widget.dart file:
import 'package:amazon/utils/constants.dart';
import 'package:flutter/material.dart';
class SearchBarWidget extends StatelessWidget with PreferredSizeWidget {
SearchBarWidget({Key? key}) : preferredSize = Size.fromHeight(kAppBarHeight), super(key: key);
@override
final Size preferredSize;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.pink,
);
}
}
Here is the error message:The class 'PreferredSizeWidget' can't be used as a mixin because it's neither a mixin class nor a mixin.
I tried to change the class SearchBarWidget extends StatelessWidget with PreferredSizeWidget
code into class SearchBarWidget extends StatelessWidget implements PreferredSizeWidget
and it doesn’t give any error but still I can’t see any pink container. I also tried this code for the search_bar_widget.dart
class SearchBarWidget extends StatelessWidget {
const SearchBarWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(80.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[Colors.blue, Colors.pink],
),
),
//child: const AppBarContent(),
),
),
body: const Center(
child: Text('Content'),
),
);
}
}
But this time home_screen.dart gives this error: The argument type 'SearchBarWidget' can't be assigned to the parameter type 'PreferredSizeWidget?'.
I would be grateful if you help.
2
Answers
maybe you could try this
Add a Size to preferredSize, for example like this, that worked for me:
And also implement PreferredSizeWidget to your class
Use
kToolbarHeight
as @Ampersanda proposedFixing the PreferredSizeWidget Mixin Issue:
Instead of using with (mixin) for PreferredSizeWidget, you should use implements since PreferredSizeWidget is an interface and not a mixin. Your initial attempt was on the right track
search_bar_widget.dart:
Notes:
home_screen.dart:
No changes needed.